//
//  ShowSearchViewController.m
//  FlowerRainGround
//
//  Created by lanou on 16/4/27.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "ShowSearchViewController.h"
#import "MallModel.h"
#import "SearchCollectionViewCell.h"
#import "JingShowViewController.h"
@interface ShowSearchViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) NSMutableArray *searchArray;
@property (nonatomic, strong) UICollectionView *collectionView;
@end

@implementation ShowSearchViewController

-(NSMutableArray *)searchArray
{
    if (!_searchArray) {
        self.searchArray = [@[] mutableCopy];
    }
    return _searchArray;
}


- (void) searchData{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.searchTitile forKey:@"fnName"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //AFJSONRequestSerializer’是AFHTTPRequestSerializer的一个子类 JSON编码的参数,使用“NSJSONSerialization”,设置“内容类型的编码请求的应用程序/
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [manager POST:@"http://ec.htxq.net/rest/htxq/goods/search" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dic1 = dic[@"result"];
        for (NSDictionary *dic2 in dic1[@"result"]) {
            MallModel *modle = [[MallModel alloc] init];
            [modle setValuesForKeysWithDictionary:dic2];
            [self.searchArray addObject:modle];
            NSLog(@"%@", modle.fnEnName);
        }
        
        

        
       dispatch_async(dispatch_get_main_queue(), ^{
           [self searchResult];//执行看有没有数据。没有弹框
           [self.collectionView reloadData];
       });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
    
}


//创建collerctonView
- (void) creatCollectionView
{
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    flowlayout.itemSize = CGSizeMake((kWidth - 30) / 2, (kWidth - 30)/ 2 + 65);
    flowlayout.minimumInteritemSpacing = 10;
    flowlayout.minimumLineSpacing = 10;
    flowlayout.sectionInset = UIEdgeInsetsMake(0, 10, 10, 10);
    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowlayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    //xib时用Nib
    
//    [self.collectionView registerNib:[UINib nibWithNibName:@"SearchCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"reuse"];
    
    [self.collectionView registerClass:[SearchCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    
}



- (void) searchResult
{
    if (self.searchArray.count <= 0) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"无搜索结果" message:@"请检查搜索词语" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }else{
        [self creatCollectionView];
    }
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"搜索结果";
    
    [self searchData];
    
    
    
    // Do any additional setup after loading the view from its nib.
}


- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSLog(@"%ld", self.searchArray.count);
    return self.searchArray.count;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *reuse = @"reuse";
    
    SearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuse forIndexPath:indexPath];
    MallModel *model = self.searchArray[indexPath.row];
    cell.mallmodel = model;
    NSLog(@"%@", cell.mallmodel.fnEnName);
    return cell;
}


- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    JingShowViewController *VC = [[JingShowViewController alloc] init];
    VC.mallmodel = self.searchArray[indexPath.row];
    VC.typeID = 1;
    [self.navigationController pushViewController:VC animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
